﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;

namespace OhMyGol.UI.Models.Grid
{
    [ModelBinder(typeof(GridCriteriaModelBinder))]
    public class GridCriteria
    {
        public bool IsSearch { get; set; }

        public int PageIndex { get; set; }

        public int PageSize { get; set; }

        public string SortColumn { get; set; }

        public string SortOrder { get; set; }

        public IQueryable<R> Sort<R>(IQueryable<R> items)
        {
            string methodName = string.Format("OrderBy{0}",
                this.SortOrder.ToLower() == "asc" ? "" : "descending");

            ParameterExpression parameter = Expression.Parameter(items.ElementType, "p");

            MemberExpression memberAccess = null;
            foreach (var property in this.SortColumn.Split('.'))
                memberAccess = MemberExpression.Property
                   (memberAccess ?? (parameter as Expression), property);

            LambdaExpression orderByLambda = Expression.Lambda(memberAccess, parameter);

            MethodCallExpression result = Expression.Call(
                      typeof(Queryable),
                      methodName,
                      new[] { items.ElementType, memberAccess.Type },
                      items.Expression,
                      Expression.Quote(orderByLambda));

            return items.Provider.CreateQuery<R>(result);
        }

        public IQueryable<R> Page<R>(IQueryable<R> items)
        {
            return items.Skip((this.PageIndex - 1) * this.PageSize).Take(this.PageSize);
        }

        public int PagesCount(int totalRowsCount)
        {
            return (int)Math.Ceiling((double)totalRowsCount / this.PageSize);
        }
    }
}